package cn.wjx.taobaounion.ui.fragment;

import android.graphics.Rect;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.wjx.taobaounion.R;
import cn.wjx.taobaounion.base.BaseFragment;
import cn.wjx.taobaounion.model.domain.Histories;
import cn.wjx.taobaounion.model.domain.IBaseGoodsItemInfo;
import cn.wjx.taobaounion.model.domain.SearchRecommend;
import cn.wjx.taobaounion.model.domain.SearchResult;
import cn.wjx.taobaounion.presenter.ISearchPresenter;
import cn.wjx.taobaounion.ui.adapter.HomeContentListAdapter;
import cn.wjx.taobaounion.ui.custom.FlowTextLayout;
import cn.wjx.taobaounion.utils.KeyboardUtil;
import cn.wjx.taobaounion.utils.LogUtils;
import cn.wjx.taobaounion.utils.PresenterManger;
import cn.wjx.taobaounion.utils.TicketUtil;
import cn.wjx.taobaounion.utils.ToastUtil;
import cn.wjx.taobaounion.view.ISearchPageCallback;

/**
 * @author WuChangJian
 * @date 2020/6/16 21:07
 */
public class SearchFragment extends BaseFragment implements ISearchPageCallback, HomeContentListAdapter.OnItemClickListener, FlowTextLayout.OnFlowTextItemClickListener {


    private ISearchPresenter mSearchPresenter;
    @BindView(R.id.search_history_container)
    public LinearLayout historyContainer;
    @BindView(R.id.search_history_view)
    public FlowTextLayout historyRecord;
    @BindView(R.id.search_recommend_container)
    public LinearLayout recommendContainer;
    @BindView(R.id.search_recommend_view)
    public FlowTextLayout recommendRecord;
    @BindView(R.id.search_history_delete)
    public ImageView historyDelete;
    @BindView(R.id.search_result_list)
    public RecyclerView searchResultList;
    @BindView(R.id.search_result_container)
    public TwinklingRefreshLayout refreshContainer;
    @BindView(R.id.search_input_box)
    public EditText searchInput;
    @BindView(R.id.search_clean_btn)
    public ImageView cleanBtn;
    @BindView(R.id.search_btn)
    public TextView searchBtn;

    private HomeContentListAdapter mContentListAdapter;

    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_search;
    }

    @Override
    protected View loadRootView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_with_bar_search, container, false);
    }

    @Override
    protected void initView(View rootView) {
        //mSearchPageAdapter = new SearchPageAdapter();
        // 复用HomeContentListAdapter
        mContentListAdapter = new HomeContentListAdapter();
        searchResultList.setLayoutManager(new LinearLayoutManager(getContext()));
        searchResultList.setAdapter(mContentListAdapter);
        searchResultList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = 8;
                outRect.bottom = 8;//px
            }
        });
        refreshContainer.setEnableRefresh(false);
        refreshContainer.setEnableLoadmore(true);

    }

    @Override
    protected void initListener() {
        mContentListAdapter.setOnItemClickListener(this);
        // 历史记录 热词的监听
        recommendRecord.setOnFlowTextItemClickListener(this);
        historyRecord.setOnFlowTextItemClickListener(this);
        historyDelete.setOnClickListener(v-> {
            if (mSearchPresenter != null) {
                // 删除历史记录
                mSearchPresenter.delHistories();
            }
        });
        refreshContainer.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                if (mSearchPresenter != null) {
                    mSearchPresenter.loaderMore();
                }
            }
        });
        searchBtn.setOnClickListener(v-> {
            if (hasInput(false)) {
                if (mSearchPresenter != null) {
                    //mSearchPresenter.doSearch(searchInput.getText().toString().trim());
                    toSearch(searchInput.getText().toString().trim());
                    // 搜索点击后 hide keyboard
                    KeyboardUtil.hide(getContext(), v);
                }
            } else {
                // 取消 这里就是隐藏键盘 开发根据PM设计
                KeyboardUtil.hide(getContext(), v);
            }
        });
        searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH && mSearchPresenter != null) {
                    String keyword = v.getText().toString().trim();
                    LogUtils.d(SearchFragment.this, "keyword -->" + keyword);
                    if (TextUtils.isEmpty(keyword)) {
                        return false;
                    }
                    // 键盘布局中的搜索
                    //mSearchPresenter.doSearch(keyword);
                    toSearch(keyword);
                }
                return false;
            }
        });
        // 监听输入框内容变换
        searchInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 如果输入框有输入内容，则显示删除按钮，否则隐藏
                cleanBtn.setVisibility(hasInput(true)? View.VISIBLE : View.GONE);
                searchBtn.setText(hasInput(false) ? "搜索" : "取消");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        // 清空搜索内容
        cleanBtn.setOnClickListener(v-> {
            searchInput.setText("");
            // 回到历史记录界面
            switch2Histories();
        });
    }

    private void switch2Histories() {
        if (mSearchPresenter != null) {
            mSearchPresenter.getHistories();
        }
        recommendContainer.setVisibility(recommendRecord.isEmpty() ? View.GONE : View.VISIBLE);
        refreshContainer.setVisibility(View.GONE);
    }

    private boolean hasInput(boolean containSpace) {
        if (containSpace) {
            return searchInput.getText().toString().length() > 0;
        } else {
            return searchInput.getText().toString().trim().length() > 0;
        }
    }

    @Override
    protected void initPresenter() {
        mSearchPresenter = PresenterManger.getInstance().getSearchPresenter();
        mSearchPresenter.registerViewCallback(this);
    }

    @Override
    protected void loadData() {
        mSearchPresenter.getRecommendWords();
        mSearchPresenter.getHistories();
        //mSearchPresenter.doSearch("电脑");
    }

    @Override
    public void onHistoriesLoaded(Histories histories) {
        if (histories != null && histories.getHistories() != null && histories.getHistories().size() > 0) {
            historyContainer.setVisibility(View.VISIBLE);
            historyRecord.setTextList(histories.getHistories());
        } else {
            historyContainer.setVisibility(View.GONE);
        }
    }

    @Override
    public void onHistoriesDeleted() {
        if (mSearchPresenter != null) {
            mSearchPresenter.getHistories();
        }
    }

    @Override
    public void onRecommendWordsLoaded(List<SearchRecommend.DataBean> words) {
        setUpState(State.SUCCESS);
        List<String> recommendKeywords = new ArrayList<>();
        for(SearchRecommend.DataBean item : words) {
            recommendKeywords.add(item.getKeyword());
        }
        if(words.size() == 0) {
            recommendContainer.setVisibility(View.GONE);
        } else {
            recommendRecord.setTextList(recommendKeywords);
            recommendContainer.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onSearchSuccess(SearchResult searchResult) {
        setUpState(State.SUCCESS);
        //LogUtils.d(this, " search result-->" + searchResult.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data().size());
        // 搜索成功 隐藏搜索历史和推荐词布局 显示搜索结果的布局
        historyContainer.setVisibility(View.GONE);
        recommendContainer.setVisibility(View.GONE);
        refreshContainer.setVisibility(View.VISIBLE);
        mContentListAdapter.setData(searchResult.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data());
    }

    @Override
    public void onLoaderMore(SearchResult searchResult) {
        List<SearchResult.DataBean.TbkDgMaterialOptionalResponseBean.ResultListBean.MapDataBean> data = searchResult.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data();
        //LogUtils.d(this, "onLoaderMore... size-->"+ data.size());
        if (refreshContainer != null) {
            ToastUtil.showToast("加载了"+data.size()+"条数据");
            mContentListAdapter.addData(data);
            refreshContainer.finishLoadmore();
        }
    }

    @Override
    public void onLoaderMoreError() {
        ToastUtil.showToast("加载数据失败,请稍候重试");
        if (refreshContainer != null) {
            refreshContainer.finishLoadmore();
        }
    }

    @Override
    public void onLoaderMoreEmpty() {
        ToastUtil.showToast("加载数据为空");
        if (refreshContainer != null) {
            refreshContainer.finishLoadmore();
        }
    }

    @Override
    public void reload() {
        if (mSearchPresenter != null) {
            mSearchPresenter.reSearch();
        }
    }

    @Override
    public void onError() {
        setUpState(State.ERROR);
    }

    @Override
    public void onLoading() {
        setUpState(State.LOADING);
    }

    @Override
    public void onEmpty() {
        setUpState(State.EMPTY);
    }

    @Override
    protected void release() {
        if (mSearchPresenter != null) {
            mSearchPresenter.unregisterViewCallback(this);
        }
    }

    @Override
    public void OnItemClick(IBaseGoodsItemInfo item) {
        // 跳转到淘口令界面
        TicketUtil.toTicketPage(getContext(), item);
    }

    @Override
    public void onFlowTextItemClick(String text) {
        searchInput.setText(text);
        toSearch(text);

    }

    private void toSearch(String keyword) {
        searchInput.setFocusable(true);
        searchInput.setSelection(keyword.length(), keyword.length());
        if (searchResultList != null) {
            searchResultList.scrollToPosition(0);
        }
        if (mSearchPresenter != null) {
            mSearchPresenter.doSearch(keyword);
        }
    }
}
